
# pages/admin.py - 管理员页面
import streamlit as st
from st_pages import add_page_title
import json
import os
from datetime import datetime, timedelta
import pandas as pd
from utils.helpers import check_authentication, get_user_role, log_user_activity

# 检查认证状态
check_authentication()

# 检查管理员权限
current_user = st.session_state.get('username', '')
if get_user_role(current_user) != 'admin':
    st.error("🚫 您没有权限访问管理员页面!")
    st.stop()

add_page_title()

# 记录页面访问
log_user_activity(current_user, 'page_visit', 'admin')

st.markdown("### 👑 系统管理")

# 管理员导航
admin_tab1, admin_tab2, admin_tab3, admin_tab4 = st.tabs([
    "用户管理", "系统监控", "日志查看", "系统设置"
])

with admin_tab1:
    st.subheader("👥 用户管理")
    
    # 用户列表
    col1, col2 = st.columns([2, 1])
    
    with col1:
        st.markdown("#### 活跃用户")
        
        # 模拟用户数据
        users_data = [
            {"用户名": "admin", "姓名": "管理员", "角色": "管理员", "状态": "在线", "最后登录": "2024-01-15 10:30"},
            {"用户名": "user1", "姓名": "用户一", "角色": "用户", "状态": "离线", "最后登录": "2024-01-14 16:45"},
            {"用户名": "user2", "姓名": "用户二", "角色": "用户", "状态": "在线", "最后登录": "2024-01-15 09:15"},
        ]
        
        users_df = pd.DataFrame(users_data)
        st.dataframe(users_df, use_container_width=True)
        
        # 用户操作
        selected_user = st.selectbox("选择用户进行操作", users_df["用户名"].tolist())
        
        col_a, col_b, col_c = st.columns(3)
        with col_a:
            if st.button("重置密码"):
                st.success(f"已为用户 {selected_user} 重置密码")
        with col_b:
            if st.button("禁用账户"):
                st.warning(f"已禁用用户 {selected_user}")
        with col_c:
            if st.button("删除用户"):
                st.error(f"已删除用户 {selected_user}")
    
    with col2:
        st.markdown("#### 快速统计")
        
        st.metric("总用户数", "15", "↑2")
        st.metric("活跃用户", "8", "↑1") 
        st.metric("今日新增", "2", "↑2")
        st.metric("在线用户", "5", "↓1")
        
        st.markdown("#### 添加新用户")
        
        with st.form("add_user_form"):
            new_username = st.text_input("用户名")
            new_name = st.text_input("姓名")
            new_email = st.text_input("邮箱")
            new_role = st.selectbox("角色", ["user", "admin"])
            new_password = st.text_input("初始密码", type="password")
            
            if st.form_submit_button("添加用户"):
                if new_username and new_password:
                    st.success(f"用户 {new_username} 已成功添加!")
                else:
                    st.error("请填写必要信息!")

with admin_tab2:
    st.subheader("📊 系统监控")
    
    # 系统状态指标
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        st.metric(
            label="CPU使用率",
            value="45%",
            delta="↑5%"
        )
    
    with col2:
        st.metric(
            label="内存使用率", 
            value="68%",
            delta="↑12%"
        )
    
    with col3:
        st.metric(
            label="磁盘使用率",
            value="23%", 
            delta="↑2%"
        )
    
    with col4:
        st.metric(
            label="网络I/O",
            value="1.2MB/s",
            delta="↓0.3MB/s"
        )
    
    st.divider()
    
    # 系统性能图表
    import plotly.graph_objects as go
    import numpy as np
    
    # 生成模拟性能数据
    times = pd.date_range(start='2024-01-15 00:00', end='2024-01-15 23:59', freq='H')
    cpu_usage = np.random.normal(45, 10, len(times))
    memory_usage = np.random.normal(65, 8, len(times))
    
    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=times, y=cpu_usage,
        mode='lines', name='CPU使用率(%)',
        line=dict(color='red', width=2)
    ))
    fig.add_trace(go.Scatter(
        x=times, y=memory_usage,
        mode='lines', name='内存使用率(%)',
        line=dict(color='blue', width=2)
    ))
    
    fig.update_layout(
        title="系统性能监控 - 24小时",
        xaxis_title="时间",
        yaxis_title="使用率 (%)",
        hovermode='x unified'
    )
    
    st.plotly_chart(fig, use_container_width=True)
    
    # 服务状态
    st.markdown("#### 🔧 服务状态")
    
    services_status = [
        {"服务": "Web服务器", "状态": "🟢 运行中", "端口": "8501", "启动时间": "2024-01-15 08:00"},
        {"服务": "数据库", "状态": "🟢 运行中", "端口": "5432", "启动时间": "2024-01-15 08:01"},
        {"服务": "Redis缓存", "状态": "🟡 警告", "端口": "6379", "启动时间": "2024-01-15 08:02"},
        {"服务": "文件存储", "状态": "🟢 运行中", "端口": "9000", "启动时间": "2024-01-15 08:03"},
    ]
    
    services_df = pd.DataFrame(services_status)
    st.dataframe(services_df, use_container_width=True)

with admin_tab3:
    st.subheader("📋 系统日志")
    
    # 日志类型选择
    log_type = st.selectbox(
        "选择日志类型",
        ["用户活动", "系统错误", "安全事件", "性能日志"]
    )
    
    # 日志时间范围
    col1, col2 = st.columns(2)
    with col1:
        start_date = st.date_input("开始日期", value=datetime.now().date() - timedelta(days=7))
    with col2:
        end_date = st.date_input("结束日期", value=datetime.now().date())
    
    # 模拟日志数据
    if log_type == "用户活动":
        log_data = [
            {"时间": "2024-01-15 10:30:22", "用户": "admin", "操作": "登录", "页面": "main", "IP": "192.168.1.100"},
            {"时间": "2024-01-15 10:25:15", "用户": "user1", "操作": "查看", "页面": "dashboard", "IP": "192.168.1.101"},
            {"时间": "2024-01-15 10:20:33", "用户": "admin", "操作": "导出", "页面": "data_analysis", "IP": "192.168.1.100"},
            {"时间": "2024-01-15 10:15:44", "用户": "user2", "操作": "上传", "页面": "data_analysis", "IP": "192.168.1.102"},
        ]
    elif log_type == "系统错误":
        log_data = [
            {"时间": "2024-01-15 09:45:12", "级别": "ERROR", "模块": "数据库", "消息": "连接超时", "详情": "Connection timeout after 30s"},
            {"时间": "2024-01-15 08:30:22", "级别": "WARN", "模块": "文件系统", "消息": "磁盘空间不足", "详情": "Disk usage > 80%"},
            {"时间": "2024-01-15 07:15:33", "级别": "ERROR", "模块": "认证", "消息": "登录失败", "详情": "Invalid credentials for user: test"},
        ]
    elif log_type == "安全事件":
        log_data = [
            {"时间": "2024-01-15 11:00:15", "事件": "登录失败", "用户": "unknown", "IP": "10.0.0.1", "风险": "中"},
            {"时间": "2024-01-15 10:30:45", "事件": "密码重置", "用户": "user1", "IP": "192.168.1.101", "风险": "低"},
            {"时间": "2024-01-15 09:15:22", "事件": "异常访问", "用户": "admin", "IP": "203.0.113.1", "风险": "高"},
        ]
    else:  # 性能日志
        log_data = [
            {"时间": "2024-01-15 11:00:00", "指标": "响应时间", "值": "250ms", "状态": "正常", "阈值": "500ms"},
            {"时间": "2024-01-15 10:55:00", "指标": "内存使用", "值": "72%", "状态": "警告", "阈值": "80%"},
            {"时间": "2024-01-15 10:50:00", "指标": "并发用户", "值": "15", "状态": "正常", "阈值": "100"},
        ]
    
    logs_df = pd.DataFrame(log_data)
    st.dataframe(logs_df, use_container_width=True)
    
    # 日志导出
    if st.button("导出日志"):
        csv = logs_df.to_csv(index=False)
        st.download_button(
            label="下载CSV文件",
            data=csv,
            file_name=f"{log_type}_logs_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv",
            mime="text/csv"
        )

with admin_tab4:
    st.subheader("⚙️ 系统设置")
    
    # 系统配置
    config_tab1, config_tab2, config_tab3 = st.tabs(["基本设置", "安全设置", "备份设置"])
    
    with config_tab1:
        st.markdown("#### 🏠 应用配置")
        
        col1, col2 = st.columns(2)
        
        with col1:
            app_name = st.text_input("应用名称", value="我的应用程序")
            app_version = st.text_input("应用版本", value="1.0.0")
            debug_mode = st.checkbox("调试模式", value=False)
            
        with col2:
            max_users = st.number_input("最大用户数", value=100, min_value=1)
            session_timeout = st.number_input("会话超时(分钟)", value=30, min_value=5)
            auto_logout = st.checkbox("自动登出", value=True)
        
        st.markdown("#### 🎨 界面配置")
        
        default_theme = st.selectbox("默认主题", ["浅色", "深色", "自动"], index=0)
        logo_url = st.text_input("Logo URL", value="")
        custom_css = st.text_area("自定义CSS", placeholder="/* 自定义样式 */")
    
    with config_tab2:
        st.markdown("#### 🔐 密码策略")
        
        min_password_length = st.slider("最小密码长度", 6, 20, 8)
        require_special_chars = st.checkbox("需要特殊字符", value=True)
        require_numbers = st.checkbox("需要数字", value=True)
        password_expiry = st.number_input("密码过期天数", value=90, min_value=0)
        
        st.markdown("#### 🛡️ 访问控制")
        
        max_login_attempts = st.number_input("最大登录尝试次数", value=5, min_value=1)
        lockout_duration = st.number_input("锁定持续时间(分钟)", value=15, min_value=1)
        ip_whitelist = st.text_area("IP白名单", placeholder="192.168.1.0/24\n10.0.0.0/8")
        
        st.markdown("#### 📊 审计设置")
        
        enable_audit_log = st.checkbox("启用审计日志", value=True)
        log_retention_days = st.number_input("日志保留天数", value=90, min_value=1)
    
    with config_tab3:
        st.markdown("#### 💾 备份配置")
        
        auto_backup = st.checkbox("启用自动备份", value=True)
        
        if auto_backup:
            backup_frequency = st.selectbox(
                "备份频率", 
                ["每天", "每周", "每月"], 
                index=0
            )
            backup_time = st.time_input("备份时间", value=datetime.now().time().replace(hour=2, minute=0, second=0))
            backup_retention = st.number_input("备份保留份数", value=30, min_value=1)
        
        st.markdown("#### 📤 备份存储")
        
        backup_location = st.selectbox(
            "备份位置",
            ["本地存储", "阿里云OSS", "腾讯云COS", "AWS S3"],
            index=0
        )
        
        if backup_location != "本地存储":
            access_key = st.text_input("Access Key", type="password")
            secret_key = st.text_input("Secret Key", type="password")
            bucket_name = st.text_input("存储桶名称")
        
        # 立即备份
        if st.button("立即执行备份", type="primary"):
            with st.spinner("正在执行备份..."):
                import time
                time.sleep(2)  # 模拟备份过程
            st.success("备份已完成!")
    
    st.divider()
    
    # 保存设置
    col1, col2, col3 = st.columns([1, 1, 1])
    
    with col1:
        if st.button("保存所有设置", type="primary", use_container_width=True):
            st.success("系统设置已保存!")
    
    with col2:
        if st.button("恢复默认设置", type="secondary", use_container_width=True):
            st.warning("设置已恢复为默认值!")
    
    with col3:
        if st.button("重启系统", type="secondary", use_container_width=True):
            st.info("系统重启请求已提交!")